﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections.Generic;

using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.ConversionTools;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalyst;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Geoprocessor;

namespace SPAS
{
    enum MouseOperation
    {
        Default = 1,
        ZoomIn = 2,
        ZoomOut = 3,
        Pan = 4,

        SelectPoint,     // 角度交会选择交汇点
        SelectArea,      // 角度交会选择测区

        AddStopPoint,    // 路径规划添加站点

        SelectGNSSPoint,    // 添加GNSS控制点
    }

    public sealed partial class MainForm : Form
    {
        #region class private members
        private IMapControl3 m_mapControl = null;
        private string m_mapDocumentName = string.Empty;

        IFeatureLayer tocFeatureLayer = null;           //点击的要素图层
        private AttributeForm attributeForm = null;     //图层属性窗体

        public ArrayList costAttribut = new ArrayList();    // 成本列表
        public IFeatureClass inputFClass;                   // 水准点点要素集
        public int stationCount;                            // 水准点数
        public int PointCount = 0;                          // 已添加水准点个数
        public IGraphicsContainer PGC;                      // 不知道是啥，显示内容
        public IPoint ipFirst;                              // 闭合需要用到的起始点
        public INAContext m_NAContext;                      // 网络分析上下文
        public bool IsClose = false;                        // 是否闭合
        public IFeatureLayer stationLayer;                  // 站点点图层 

        public double GNSSAngle = 15;

        private MouseOperation mouseOperation = MouseOperation.Default;

        //Deace
        //打开shp图层
        private GNSSEdit mEdit;
        public string strOutputPath;
        public string pFilePath;
        public string pFilePath1;
        GNSSLineEdit GNSSLE = new GNSSLineEdit();
        //定义点的起点，与终点
        ArrayList point_start_x = new ArrayList();
        ArrayList point_start_y = new ArrayList();
        ArrayList point_stop_x = new ArrayList();
        ArrayList point_stop_y = new ArrayList();

        //创建要素图层
        IFeatureLayer pFeatureLayer = new FeatureLayerClass();
        bool editable = false;
        private IPointCollection mPointCollection;
        IFeatureLayer pFeatureLayer_point;
        IFeatureLayer pFeatureLayer_line;

        #endregion

        #region class constructor
        public MainForm()
        {
            InitializeComponent();
        }
        #endregion

        private void MainForm_Load(object sender, EventArgs e)
        {
            string tempDir = Utils.GetTempDirectory();
            if (System.IO.Directory.Exists(tempDir))
            {
                Utils.DeleteDirectory(tempDir);
            }

            //get the MapControl
            m_mapControl = (IMapControl3)axMapControl1.Object;

            //Deace
            menuSaveDoc.Enabled = false;
            GNSSLE.cboTasks.Items.Add("新建");
            GNSSLE.cboTasks.Items.Add("移动");
            GNSSLE.cboTasks.Items.Add("删除");
            GNSSLE.cboTasks.SelectedIndex = 0;

            //开始编辑之前，将编辑按钮设为不可用
            GNSSLE.cboTasks.Enabled = false;
            GNSSLE.btnSave.Enabled = false;
            GNSSLE.btnStopEditing.Enabled = false;
        }

        #region Main Menu event handlers
        private void menuNewDoc_Click(object sender, EventArgs e)
        {
            //execute New Document command
            ICommand command = new CreateNewDocument();
            command.OnCreate(m_mapControl.Object);
            command.OnClick();
        }

        private void menuOpenDoc_Click(object sender, EventArgs e)
        {
            //execute Open Document command
            ICommand command = new ControlsOpenDocCommandClass();
            command.OnCreate(m_mapControl.Object);
            command.OnClick();
        }

        private void menuSaveDoc_Click(object sender, EventArgs e)
        {
            //execute Save Document command
            if (m_mapControl.CheckMxFile(m_mapDocumentName))
            {
                //create a new instance of a MapDocument
                IMapDocument mapDoc = new MapDocumentClass();
                mapDoc.Open(m_mapDocumentName, string.Empty);

                //Make sure that the MapDocument is not readonly
                if (mapDoc.get_IsReadOnly(m_mapDocumentName))
                {
                    MessageBox.Show("Map document is read only!");
                    mapDoc.Close();
                    return;
                }

                //Replace its contents with the current map
                mapDoc.ReplaceContents((IMxdContents)m_mapControl.Map);

                //save the MapDocument in order to persist it
                mapDoc.Save(mapDoc.UsesRelativePaths, false);

                //close the MapDocument
                mapDoc.Close();
            }
        }

        private void menuSaveAs_Click(object sender, EventArgs e)
        {
            //execute SaveAs Document command
            ICommand command = new ControlsSaveAsDocCommandClass();
            command.OnCreate(m_mapControl.Object);
            command.OnClick();
        }

        private void menuExitApp_Click(object sender, EventArgs e)
        {
            //exit the application
            Application.Exit();
        }
        #endregion

        //listen to MapReplaced evant in order to update the statusbar and the Save menu
        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            //get the current document name from the MapControl
            m_mapDocumentName = m_mapControl.DocumentFilename;

            //if there is no MapDocument, diable the Save menu and clear the statusbar
            if (m_mapDocumentName == string.Empty)
            {
                menuSaveDoc.Enabled = false;
                statusBarXY.Text = string.Empty;
            }
            else
            {
                //enable the Save manu and write the doc name to the statusbar
                menuSaveDoc.Enabled = true;
                statusBarXY.Text = System.IO.Path.GetFileName(m_mapDocumentName);
            }
        }

        #region 杨斯淋编写
        private void menuOpenShpFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开矢量数据文件";
            openFileDialog.Filter = "矢量数据文件(*.shp)|*.shp";
            if (openFileDialog.ShowDialog() == DialogResult.OK && openFileDialog.CheckFileExists == true)
            {
                ILayer layer = Utils.LoadShapeFile(openFileDialog.FileName);
                m_mapControl.AddLayer(layer);
                m_mapControl.Refresh();
            }
        }

        private void menuOpenRasterFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开栅格文件";
            openFileDialog.Filter = "栅格文件 (*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img";
            if (openFileDialog.ShowDialog() == DialogResult.OK && openFileDialog.CheckFileExists == true)
            {
                ILayer layer = Utils.LoadRasterFile(openFileDialog.FileName);
                m_mapControl.AddLayer(layer);
                m_mapControl.Refresh();
            }
        }

        private void menuSunSimulation_Click(object sender, EventArgs e)
        {
            ShadowSimForm ssf = new ShadowSimForm();
            ssf.mapcontrol = m_mapControl;
            ssf.Show();
        }
        #endregion

        # region 周羿、汤焱编写
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
        }

        /// <summary>
        /// 测角交会交汇点选取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSelectPoint_Click(object sender, EventArgs e)
        {
            m_mapControl.CurrentTool = null;
            mouseOperation = MouseOperation.SelectPoint;
            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }

        /// <summary>
        /// 矩形测区选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSelectArea_Click(object sender, EventArgs e)
        {
            m_mapControl.CurrentTool = null;
            mouseOperation = MouseOperation.SelectArea;
            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerArrow;
        }

        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            //Deace
            if (mEdit != null)
            {
                if (mEdit.IsEditing())
                {
                    switch (GNSSLE.cboTasks.SelectedIndex)
                    {
                        case 0:
                            mEdit.CreateMouseDown(e.mapX, e.mapY);
                            break;
                        case 1:
                            mEdit.PanMouseDown(e.mapX, e.mapY);
                            break;
                        case 2:
                            mEdit.DeleteMouseDown(e.mapX, e.mapY);
                            break;
                    }
                }
            }
            //Deace
            if (editable == true)
            {
                if (mPointCollection == null)
                    mPointCollection = new MultipointClass();

                //记录鼠标点击的点
                IPoint pNewPoint = new PointClass();
                pNewPoint.PutCoords(Convert.ToDouble(e.mapX), Convert.ToDouble(e.mapY));
                //MessageBox.Show(e.mapX.ToString());
                //添加点，before和after标记添加点的索引，这里不定义
                object before = Type.Missing;
                object after = Type.Missing;
                mPointCollection.AddPoint(pNewPoint, ref before, ref after);
                axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                IGeometry pt = pNewPoint as IGeometry;
                IMarkerElement markerelement = new MarkerElementClass();
                IElement element = markerelement as IElement;
                element.Geometry = pt;

                IGraphicsContainer graphicscontainer = axMapControl1.Map as IGraphicsContainer;
                graphicscontainer.AddElement((IElement)markerelement, 0);
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
            if (e.button == 1)  // 鼠标坐标点击
            {
                switch (mouseOperation)
                {
                    case MouseOperation.Default:
                        {
                            m_mapControl.CurrentTool = null;
                            break;
                        }
                    case MouseOperation.ZoomIn:
                        {
                            break;
                        }
                    case MouseOperation.ZoomOut:
                        {
                            break;
                        }
                    case MouseOperation.Pan:
                        {
                            m_mapControl.Pan();
                            break;
                        }
                    case MouseOperation.SelectPoint:
                        {
                            IFeatureLayer pointLayer = Utils.GetLayerByName(m_mapControl, "交会点");
                            if (pointLayer == null)
                            {
                                string tempFilePath = Utils.GetTempDirectory();
                                tempFilePath = tempFilePath + "交会点.shp";
                                pointLayer = Utils.AddFeatureLayer(tempFilePath, esriGeometryType.esriGeometryPoint);
                                m_mapControl.AddLayer(pointLayer);
                                Utils.ChangePointLayerStyle(pointLayer, Color.Red, esriSimpleMarkerStyle.esriSMSDiamond, 10);
                                axTOCControl1.Update();
                            }
                            else
                            {
                                if (pointLayer.FeatureClass.FeatureCount(null) > 0)
                                {
                                    ITable pointLayerTable = pointLayer as ITable;
                                    pointLayerTable.DeleteSearchedRows(null);
                                }
                            }
                            IPoint point = new ESRI.ArcGIS.Geometry.Point();
                            point.SpatialReference = m_mapControl.SpatialReference;
                            point.PutCoords(e.mapX, e.mapY);
                            Utils.AddGeometry(point, pointLayer);
                            m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

                            mouseOperation = MouseOperation.Default;
                            break;
                        }
                    case MouseOperation.SelectArea:
                        {
                            // 获取用户选择的矩形区域
                            IEnvelope rec = axMapControl1.TrackRectangle();

                            IFeatureLayer recLayer = Utils.GetLayerByName(m_mapControl, "交会测区");
                            if (recLayer == null)
                            {
                                string tempFilePath = Utils.GetTempDirectory();
                                tempFilePath = tempFilePath + "交会测区.shp";
                                recLayer = Utils.AddFeatureLayer(tempFilePath, esriGeometryType.esriGeometryPolygon);
                                m_mapControl.AddLayer(recLayer);
                                Utils.ChangePolygonLayerStyle(recLayer, Color.Yellow, 2, Color.Yellow);
                                axTOCControl1.Update();
                            }
                            else
                            {
                                if (recLayer.FeatureClass.FeatureCount(null) > 0)
                                {
                                    ITable pointLayerTable = recLayer as ITable;
                                    pointLayerTable.DeleteSearchedRows(null);
                                }
                            }
                            IPointCollection pointCollection = new PolygonClass();
                            pointCollection.AddPoint(rec.UpperLeft);
                            pointCollection.AddPoint(rec.LowerLeft);
                            pointCollection.AddPoint(rec.LowerRight);
                            pointCollection.AddPoint(rec.UpperRight);
                            pointCollection.AddPoint(rec.UpperLeft);
                            IPolygon polygon = pointCollection as IPolygon;
                            polygon.SpatialReference = m_mapControl.SpatialReference;
                            Utils.AddGeometry(polygon, recLayer);
                            //m_mapControl.Refresh();
                            m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

                            mouseOperation = MouseOperation.Default;
                            break;
                        }
                    case MouseOperation.AddStopPoint:
                        {
                            bool jump = false;
                            IPointCollection m_ipPoints;//输入点集合
                            IPoint ipNew = new PointClass();
                            m_ipPoints = new MultipointClass();
                            ipNew.PutCoords(e.mapX, e.mapY);
                            if (PointCount == 0)
                            {
                                ipFirst = ipNew;
                            }
                            object o = Type.Missing;
                            m_ipPoints.AddPoint(ipNew, ref o, ref o);//添加选入点
                            //最后一点闭合
                            if (PointCount >= stationCount - 1)
                            {
                                mouseOperation = MouseOperation.Default;
                                MessageBox.Show("选点完毕");
                                if (IsClose)
                                {
                                    m_ipPoints.AddPoint(ipFirst, ref o, ref o);
                                }
                                //this.Cursor = new System.Windows.Forms.Cursor("");                              
                                jump = true;
                            }
                            CreateFeature(inputFClass, m_ipPoints);//或者用鼠标点击最近点
                            //添加自定义站点图片
                            IColor pColor;
                            IRgbColor pRgbColor = new RgbColorClass();
                            pRgbColor.Red = 255;
                            pRgbColor.Green = 255;
                            pRgbColor.Blue = 255;
                            pColor = pRgbColor as IColor;

                            IPictureMarkerSymbol pms = new PictureMarkerSymbolClass();
                            pms.BitmapTransparencyColor = pColor;
                            string picturePath = ".\\image\\stop.bmp";

                            pms.CreateMarkerSymbolFromFile(esriIPictureType.esriIPictureBitmap, picturePath);
                            pms.Size = 18;
                            IMarkerElement pMarkerEle = new MarkerElementClass();
                            pMarkerEle.Symbol = pms as IMarkerSymbol;
                            ipNew.SpatialReference = axMapControl1.ActiveView.FocusMap.SpatialReference;
                            IElement pEle = pMarkerEle as IElement;
                            pEle.Geometry = ipNew;
                            PGC.AddElement(pEle, 1);
                            //显示文本
                            IElement element;
                            ITextElement textelement = new TextElementClass();
                            element = textelement as IElement;
                            ITextSymbol textSymbol = new TextSymbol();
                            //字体颜色
                            pRgbColor.Red = 0;
                            pRgbColor.Green = 0;
                            pRgbColor.Blue = 255;
                            pColor = pRgbColor as IColor;
                            textSymbol.Color = pColor;
                            //字体大小
                            //System.Drawing.Font textFont = new System.Drawing.Font("宋体", 16, FontStyle.Bold);
                            //textSymbol.Font = OLE.GetIFontDispFromFont(textFont);
                            textSymbol.Size = 18;
                            //
                            textelement.Symbol = textSymbol;
                            textelement.Text = (PointCount + 1).ToString();
                            element.Geometry = ipNew;
                            PGC.AddElement(element, 0);
                            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                            if (!jump)
                            {
                                PointCount++;
                            }
                            else
                            {
                                PointCount = 0;
                            }
                            break;
                        }
                    case MouseOperation.SelectGNSSPoint:
                        {
                            IFeatureLayer pointLayer = Utils.GetLayerByName(m_mapControl, "GNSS控制点");
                            if (pointLayer == null)
                            {
                                string tempFilePath = Utils.GetTempDirectory();
                                tempFilePath = tempFilePath + "GNSS控制点.shp";
                                pointLayer = Utils.AddFeatureLayer(tempFilePath, esriGeometryType.esriGeometryPoint);
                                m_mapControl.AddLayer(pointLayer);
                                Utils.ChangePointLayerStyle(pointLayer, Color.Black, esriSimpleMarkerStyle.esriSMSSquare, 10);
                                axTOCControl1.Update();
                            }
                            IPoint point = new ESRI.ArcGIS.Geometry.Point();
                            point.SpatialReference = m_mapControl.SpatialReference;
                            point.PutCoords(e.mapX, e.mapY);
                            Utils.AddGeometry(point, pointLayer);
                            m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                            break;
                        }

                }
            }
            else if (e.button == 2) // 右键
            { }
            else if (e.button == 4) // 中键
            {
                m_mapControl.MousePointer = esriControlsMousePointer.esriPointerPan;
                m_mapControl.Pan();
            }
        }

        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            if (mEdit != null)
            {
                if (mEdit.IsEditing())
                {
                    switch (GNSSLE.cboTasks.SelectedIndex)
                    {
                        case 0:
                        case 1:
                            mEdit.MouseMove(e.mapX, e.mapY);
                            break;
                    }
                }
            }
            statusBarXY.Text = string.Format("{0}, {1}  {2}", e.mapX.ToString("#######.###"), e.mapY.ToString("#######.###"), axMapControl1.MapUnits.ToString().Substring(4));

            if (e.button != 4)
            {
                switch (mouseOperation)
                {
                    case MouseOperation.Default:
                        {
                            m_mapControl.CurrentTool = null;
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
                            break;
                        }
                    case MouseOperation.ZoomIn:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerPageZoomIn;
                            break;
                        }
                    case MouseOperation.ZoomOut:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerPageZoomOut;
                            break;
                        }
                    case MouseOperation.Pan:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerPan;
                            break;
                        }
                    case MouseOperation.SelectPoint:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                            break;
                        }
                    case MouseOperation.SelectArea:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerArrow;
                            break;
                        }
                    case MouseOperation.AddStopPoint:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                            break;
                        }
                    case MouseOperation.SelectGNSSPoint:
                        {
                            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                            break;
                        }
                }
            }
        }

        /// <summary>
        /// 可视分析
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuJudgeVisible_Click(object sender, EventArgs e)
        {
            IFeatureLayer pointLayer = Utils.GetLayerByName(m_mapControl, "交会点");
            if (pointLayer == null)
            {
                MessageBox.Show("未选择交会点");
                return;
            }
            IFeatureLayer rectLayer = Utils.GetLayerByName(m_mapControl, "交会测区");
            if (rectLayer == null)
            {
                MessageBox.Show("未选择交会测区");
                return;
            }

            IPoint point = Utils.GetFirstFeature(pointLayer.FeatureClass).Shape as IPoint;
            IPolygon polygon = Utils.GetFirstFeature(rectLayer.FeatureClass).Shape as IPolygon;

            IBasicMap basicMap = new Map() as IBasicMap;
            ILayer layer = new RasterLayer();
            IRasterLayer rasterLayer = new RasterLayer();
            object unk = new object();
            object data = new object();
            esriTOCControlItem tocItem = new esriTOCControlItem();
            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);
            rasterLayer = layer as IRasterLayer;

            if (rasterLayer == null)
            {
                MessageBox.Show("未选择栅格图层");
                return;
            }

            IRasterDataset resRasterDataset = Visibility.VisibilityAnalysis(point, polygon.Envelope, rasterLayer);
            IRaster resRaster;
            resRaster = resRasterDataset.CreateDefaultRaster();
            IRasterLayer resRasterLayer = new RasterLayerClass();
            resRasterLayer.CreateFromRaster(resRaster);
            Visibility.RasterUniqueRender(resRasterLayer, Color.Green, Color.Red);
            m_mapControl.AddLayer(resRasterLayer);
            m_mapControl.Refresh();
        }
        #endregion

        #region 汤焱编写
        /// <summary>
        /// 数据处理——多面体转栅格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuMultiPatchToRaster_Click(object sender, EventArgs e)
        {
            IBasicMap basicMap = new Map() as IBasicMap;
            ILayer layer = new FeatureLayer();
            IFeatureLayer multiLayer = new FeatureLayer();
            object unk = new object();
            object data = new object();
            esriTOCControlItem tocItem = new esriTOCControlItem();
            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);
            multiLayer = layer as IFeatureLayer;

            if (multiLayer == null)
            {
                MessageBox.Show("未选择图层");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存栅格文件";
            saveFileDialog.Filter = "栅格文件 (*.tif)|*.tif";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                IRaster raster = Utils.ConvertMultiPatchToRaster(multiLayer.FeatureClass, saveFileDialog.FileName);
                IRasterLayer rasterLayer = new RasterLayerClass();
                rasterLayer.CreateFromRaster(raster);
                m_mapControl.AddLayer(rasterLayer);
                m_mapControl.Refresh();
            }
        }

        /// <summary>
        /// 数据处理——多面体转面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuMultiPatchToPolygon_Click(object sender, EventArgs e)
        {
            IBasicMap basicMap = new Map() as IBasicMap;
            ILayer layer = new FeatureLayer();
            IFeatureLayer multiLayer = new FeatureLayer();
            object unk = new object();
            object data = new object();
            esriTOCControlItem tocItem = new esriTOCControlItem();
            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);
            multiLayer = layer as IFeatureLayer;

            if (multiLayer == null)
            {
                MessageBox.Show("未选择图层");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存矢量文件";
            saveFileDialog.Filter = "矢量文件 (*.shp)|*.shp";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                IFeatureClass featureClass = Utils.ConvertMultiPatchToPolygonFeatures(multiLayer.FeatureClass, saveFileDialog.FileName, (multiLayer.FeatureClass as IGeoDataset).SpatialReference);
                IFeatureLayer featureLayer = new FeatureLayerClass();
                featureLayer.FeatureClass = featureClass;
                featureLayer.Name = (featureClass as IDataset).Name;
                m_mapControl.AddLayer(featureLayer);
                m_mapControl.Refresh();
            }
        }
        #endregion

        #region 周羿编写
        private void 技术规范ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void menuGNSS_Click(object sender, EventArgs e)
        {

        }

        private void 帮助文档ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 高程控制测量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EleTecSpecification ele = new EleTecSpecification();
            ele.Show();
        }

        private void 三角交会测量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TriIntersection tri = new TriIntersection();
            tri.Show();
        }

        private void GNSS控制测量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GNSSTec GTec = new GNSSTec();
            GTec.Show();
        }
        #endregion

        #region 汤焱编写
        private void menuCreateNetworkDataset_Click(object sender, EventArgs e)
        {
            IBasicMap basicMap = new Map() as IBasicMap;
            ILayer layer = new FeatureLayer();
            IFeatureLayer featureLayer = new FeatureLayer();
            object unk = new object();
            object data = new object();
            esriTOCControlItem tocItem = new esriTOCControlItem();
            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);
            featureLayer = layer as IFeatureLayer;

            if (featureLayer == null)
            {
                MessageBox.Show("未选择图层");
                return;
            }

            Utils.CreateNetworkDataset(featureLayer.FeatureClass);
            ImportNetDataset(featureLayer.FeatureClass);
        }
        #endregion

        #region 苏鹏翔、柳伟佳编写
        private void ImportNetDataset(IFeatureClass roadFeature)
        {
            IFeatureWorkspace featureWorkspace = null;
            INetworkDataset networkDataset = null;

            try
            {
                // Open Geodatabase and network dataset
                IWorkspace workspace = Utils.OpenWorkspace(Utils.GetDefaultGDB());
                networkDataset = Utils.OpenNetworkDataset(workspace, "Transportation", (roadFeature as IDataset).Name + "_ND");
                featureWorkspace = workspace as IFeatureWorkspace;
                //Utils.AddFeatureLayer(Utils.GetDefaultGDB() + "Stop", esriGeometryType.esriGeometryPoint, null, true);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to open dataset. Error Message: " + ex.Message);
                this.Close();
                return;
            }

            // Create NAContext and NASolver
            Utils.CreateSolverContext(networkDataset, ref m_NAContext);

            // Get available cost attributes from the network dataset
            INetworkAttribute networkAttribute;
            for (int i = 0; i < networkDataset.AttributeCount; i++)
            {
                networkAttribute = networkDataset.get_Attribute(i);
                if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
                {
                    costAttribut.Add(networkAttribute.Name);
                }
            }
            // Load incidents from a feature class
            //IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("Stores");
            //LoadNetDataSet.LoadNANetworkLocations("Incidents", inputFClass, 500,m_NAContext);

            // Load facilities from a feature class
            //inputFClass = featureWorkspace.OpenFeatureClass("FireStations");
            //LoadNetDataSet.LoadNANetworkLocations("Facilities", inputFClass, 500, m_NAContext);

            //加载要进行修改的点要素图层
            Utils.AddFeatureLayer(Utils.GetDefaultGDB() + "Stop.shp", esriGeometryType.esriGeometryPoint);
            inputFClass = (Utils.LoadShapeFile(Utils.GetDefaultGDB() + "Stop.shp") as IFeatureLayer).FeatureClass;
            //inputFClass = featureWorkspace.OpenFeatureClass("Stop");
            int Count = inputFClass.FeatureCount(null);
            // 加载路线的矢量图层
            IFeatureLayer road3;
            road3 = new FeatureLayerClass();
            road3.FeatureClass = featureWorkspace.OpenFeatureClass((roadFeature as IDataset).Name);
            road3.Name = road3.FeatureClass.AliasName;
            axMapControl1.AddLayer(road3, 0);

            //加载交汇点的点图层
            IFeatureLayer vertex = new FeatureLayerClass();
            vertex.FeatureClass = featureWorkspace.OpenFeatureClass((roadFeature as IDataset).Name + "_ND_Junctions");
            vertex.Name = vertex.FeatureClass.AliasName;
            axMapControl1.AddLayer(vertex, 0);

            //Create Layer for Network Dataset and add to ArcMap
            INetworkLayer networkLayer = new NetworkLayerClass();
            networkLayer.NetworkDataset = networkDataset;
            var layer = networkLayer as ILayer;
            layer.Name = "Network Dataset";
            axMapControl1.AddLayer(layer, 0);//整体网络图

            //Create a Network Analysis Layer and add to ArcMap
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            layer = naLayer as ILayer;
            layer.Name = m_NAContext.Solver.DisplayName;
            axMapControl1.AddLayer(layer, 0);//网络分析图层       
            PGC = axMapControl1.ActiveView.FocusMap as IGraphicsContainer;
        }

        private void 参数设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LevelForm lef = new LevelForm();
            lef.mapcontrol = m_mapControl;
            lef.mainform = this;
            lef.Show();
        }

        /// <summary>
        /// 获取距离鼠标点击最近的点
        /// </summary>
        /// <param name="featureClass"></param>
        /// <param name="PointCollection"></param>
        private void CreateFeature(IFeatureClass featureClass, IPointCollection PointCollection)
        {
            //是否为点图层
            if (featureClass.ShapeType != esriGeometryType.esriGeometryPoint)
            {
                return;
            }
            //创建点要素
            for (int i = 0; i < PointCollection.PointCount; i++)
            {
                IFeature feature = featureClass.CreateFeature();
                IPoint pPoint = PointCollection.get_Point(i);
                //pPoint.Z = 0;
                feature.Shape = pPoint as IGeometry;
                IRowSubtypes rowSubtypes = (IRowSubtypes)feature;
                feature.Store();
            }
        }

        private void axTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap basicMap = null;
            ILayer layer = null;
            object unk = null;
            object data = null;
            axTOCControl1.HitTest(e.x, e.y, ref item, ref basicMap, ref layer, ref unk, ref data);
            IFeatureLayer featureLayer = layer as IFeatureLayer;

            if (featureLayer == null)
            {
                return;
            }

            if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
            {
                SymbolDesignForm symboltype = new SymbolDesignForm(2);
                symboltype.ShowDialog();
                IRgbColor rgbColor = new RgbColorClass();
                rgbColor.Red = symboltype.LineColor.R;
                rgbColor.Blue = symboltype.LineColor.B;
                rgbColor.Green = symboltype.LineColor.G;
                esriSimpleLineStyle inputStyle = symboltype.inputStyle;//实线填充
                double lineWidth = symboltype.lineWidth;
                ISimpleLineSymbol simpleLineSymbol = CreatSimpleLineSymbol(rgbColor, lineWidth, inputStyle);
                //赋值
                ISimpleRenderer pRender = new SimpleRendererClass();
                pRender.Symbol = simpleLineSymbol as ISymbol;
                (layer as IGeoFeatureLayer).Renderer = pRender as IFeatureRenderer;
                this.axMapControl1.ActiveView.Refresh();
                this.axTOCControl1.Update();
                return;
            }
            else if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                SymbolDesignForm symboltype = new SymbolDesignForm(1);
                symboltype.ShowDialog();
                IRgbColor rgbColor = new RgbColorClass();
                rgbColor.Red = symboltype.PointColor.R;
                rgbColor.Blue = symboltype.PointColor.B;
                rgbColor.Green = symboltype.PointColor.G;
                esriSimpleMarkerStyle inputStyle = symboltype.markStyle;//正方形填充
                ISimpleMarkerSymbol simpleMarkerSymbol = CreateSimpleMarkerSymbol(rgbColor, inputStyle);
                ISimpleRenderer pRender = new SimpleRendererClass();
                pRender.Symbol = simpleMarkerSymbol as ISymbol;
                (layer as IGeoFeatureLayer).Renderer = pRender as IFeatureRenderer;
                //赋值
                this.axMapControl1.ActiveView.Refresh();
                this.axTOCControl1.Update();
            }
            else if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
            {
                SymbolDesignForm symboltype = new SymbolDesignForm(3);
                symboltype.ShowDialog();
                IRgbColor rgbColorLine = new RgbColorClass();

                rgbColorLine.Red = symboltype.LineColor.R;
                rgbColorLine.Blue = symboltype.LineColor.B;
                rgbColorLine.Green = symboltype.LineColor.G;
                esriSimpleLineStyle inputStyle = symboltype.inputStyle;//实线填充
                double boderWidth = symboltype.lineWidth;
                IRgbColor rgbColorFill = new RgbColorClass();
                rgbColorFill.Red = symboltype.FillColor.R;
                rgbColorFill.Blue = symboltype.FillColor.B;
                rgbColorFill.Green = symboltype.FillColor.G;
                esriSimpleFillStyle fillStyle = symboltype.fillStyle;
                ISimpleFillSymbol simpleFillSymbol = CreateSimpleFillSymbol(rgbColorFill, fillStyle, rgbColorLine, boderWidth, inputStyle);
                //赋值
                ISimpleRenderer pRender = new SimpleRendererClass();
                pRender.Symbol = simpleFillSymbol as ISymbol;
                (layer as IGeoFeatureLayer).Renderer = pRender as IFeatureRenderer;
                this.axMapControl1.ActiveView.Refresh();
                this.axTOCControl1.Update();
            }
            else
            {
                MessageBox.Show("所选不是矢量图层");
                return;
            }
        }

        private ISimpleLineSymbol CreatSimpleLineSymbol(IRgbColor rgbColor, double inWidth, esriSimpleLineStyle inStyle)//线填充
        {

            if (rgbColor == null) { return null; }
            ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass();
            simpleLineSymbol.Color = rgbColor;
            simpleLineSymbol.Style = inStyle;
            return simpleLineSymbol;
        }
        private ISimpleMarkerSymbol CreateSimpleMarkerSymbol(IRgbColor rgbColor, esriSimpleMarkerStyle inputStyle)//点填充
        {

            if (rgbColor == null) { return null; }
            ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
            simpleMarkerSymbol.Color = rgbColor;
            simpleMarkerSymbol.Style = inputStyle;
            return simpleMarkerSymbol;
        }
        private ISimpleFillSymbol CreateSimpleFillSymbol(IRgbColor fillColor, esriSimpleFillStyle fillStyle, IRgbColor boderColor, double boderWidth, esriSimpleLineStyle borderStyle)//面填充
        {
            if (fillColor == null || boderColor == null) { return null; }
            ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass();
            simpleLineSymbol.Color = boderColor;
            simpleLineSymbol.Style = borderStyle;
            simpleLineSymbol.Width = boderWidth;
            ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol();
            simpleFillSymbol.Outline = simpleLineSymbol;
            simpleFillSymbol.Style = fillStyle;
            simpleFillSymbol.Color = fillColor;
            return simpleFillSymbol;
        }

        public void StartAddStopPoint()
        {
            m_mapControl.CurrentTool = null;
            mouseOperation = MouseOperation.AddStopPoint;
            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }

        private void 路线漫游ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (stationLayer == null)
            {
                MessageBox.Show("请先进行水准路线规划");
                return;
            }
            Level3DForm level3dform = new Level3DForm();
            level3dform.Show();

            level3dform.SceneControl.Scene.ClearLayers();

            try
            {
                level3dform.SceneControl.LoadSxFile("tongji3D\\tongji3d.sxd");
                level3dform.SceneControl.Refresh();

            }
            catch { }

            IFeatureClass routeFC = m_NAContext.NAClasses.get_ItemByName("Routes") as IFeatureClass;
            IScene pScene = level3dform.SceneControl.Scene;
            IFeatureLayer fLayer = new FeatureLayer();
            fLayer.Name = "route";
            fLayer.FeatureClass = routeFC;
            pScene.AddLayer(fLayer);
            pScene.AddLayer(stationLayer);

            //获取路径
            IFeature feature = Utils.GetFirstFeature(routeFC);
            IPolyline pPolyline = (IPolyline)feature.Shape;
            level3dform.CreateAnimationFromPath(pScene, pPolyline, 1, 10);
        }
        #endregion

        #region 杨斯淋编写
        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {
            if (e.button == 2)  // 左键
            {
                esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
                IBasicMap basicMap = null;
                ILayer layer = null;
                object unk = null;
                object data = null;
                axTOCControl1.HitTest(e.x, e.y, ref item, ref basicMap, ref layer, ref unk, ref data);
                tocFeatureLayer = layer as IFeatureLayer;

                if (item == esriTOCControlItem.esriTOCControlItemLayer && tocFeatureLayer != null)
                    contextMenuStripToc.Show(Control.MousePosition);
            }
        }

        private void menuAttribute_Click(object sender, EventArgs e)
        {
            if (attributeForm == null || attributeForm.IsDisposed)
            {
                attributeForm = new AttributeForm();
            }
            attributeForm.CurFeatureLayer = tocFeatureLayer;
            attributeForm.InitTable();
            attributeForm.ShowDialog();
        }

        private void menuZoomToLayer_Click(object sender, EventArgs e)
        {
            if (tocFeatureLayer == null) return;
            (axMapControl1.Map as IActiveView).Extent = tocFeatureLayer.AreaOfInterest;
            (axMapControl1.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }

        private void menuDeleteLayer_Click(object sender, EventArgs e)
        {
            try
            {
                if (tocFeatureLayer == null) return;
                DialogResult result = MessageBox.Show("是否删除 [" + tocFeatureLayer.Name + "] 图层", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    axMapControl1.Map.DeleteLayer(tocFeatureLayer);
                }
                axMapControl1.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 季旻编写
        private void menuCalBufferDist_Click(object sender, EventArgs e)
        {
            GNSSAngleForm gnssAngleForm = new GNSSAngleForm();
            gnssAngleForm.ShowDialog(this);

            IBasicMap basicMap = new Map() as IBasicMap;
            ILayer layer = new FeatureLayer();
            IFeatureLayer featureLayer = new FeatureLayer();
            object unk = new object();
            object data = new object();
            esriTOCControlItem tocItem = new esriTOCControlItem();
            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);
            featureLayer = layer as IFeatureLayer;

            if (featureLayer == null)
            {
                MessageBox.Show("未选择图层");
                return;
            }
            
            Utils.AddFieldToFeatureClass(featureLayer.FeatureClass, "BufferDist", esriFieldType.esriFieldTypeSingle);
            GNSS.ComputeBufferDist(featureLayer.FeatureClass, "Height", "BufferDist", GNSSAngle);
        }

        private void menuGNSSBuffer_Click(object sender, EventArgs e)
        {
            IBasicMap basicMap = new Map() as IBasicMap;
            ILayer layer = new FeatureLayer();
            IFeatureLayer featureLayer = new FeatureLayer();
            object unk = new object();
            object data = new object();
            esriTOCControlItem tocItem = new esriTOCControlItem();
            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);
            featureLayer = layer as IFeatureLayer;

            if (featureLayer == null)
            {
                MessageBox.Show("未选择图层");
                return;
            }

            string outFilePath = Utils.GetTempFilePath();
            outFilePath = System.IO.Path.ChangeExtension(outFilePath, ".shp");
            GNSS.GetGNSSFeatureClass(featureLayer.FeatureClass, outFilePath);

            ILayer resLayer = Utils.LoadShapeFile(outFilePath);
            m_mapControl.AddLayer(resLayer);
            m_mapControl.Refresh();
        }

        /// <summary>
        /// 通过GNSS控制点构建控制网
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuBuildNet_Click(object sender, EventArgs e)
        {
            IFeatureLayer pFL = Utils.GetLayerByName(m_mapControl, "GNSS控制点");
            if (pFL == null)
            {
                MessageBox.Show("未选择GNSS控制点");
                return;
            }
            //IFeatureLayer pFL = pFeatureLayer_point;//(IFeatureLayer)axMapControl1.get_Layer(0);
            IFeatureClass pFC = pFL.FeatureClass;
            IGeoDataset pGD = pFC as IGeoDataset;
            int heighIndex = pFC.FindField("id");
            IField heighField = pFC.Fields.get_Field(heighIndex);
            int idex = pFC.FindField(pFC.OIDFieldName);
            IField pField = pFC.Fields.get_Field(idex);

            ITinEdit tinEdit = new TinClass();
            tinEdit.InitNew(pGD.Extent);
            tinEdit.AddFromFeatureClass(pFC, null, heighField, pField, esriTinSurfaceType.esriTinHardLine);
            object missing = System.Type.Missing;
            tinEdit.SaveAs(System.Environment.CurrentDirectory + "\\tin1", true);
            tinEdit.Refresh();
            TinLayer tinLayer = new TinLayerClass();
            tinLayer.Dataset = tinEdit as ITinAdvanced2; ;
            ITinAdvanced pTinAdv = tinEdit as ITinAdvanced;
            int totalNum = pTinAdv.NodeCount;
            Console.WriteLine("总结点：" + totalNum.ToString());
            for (int i = 1; i <= pTinAdv.NodeCount + 2; i++)
            {
                ITinTriangle pTinTri = pTinAdv.GetTriangle(i);//triangle的index是从1开始的
                ITinNode n0 = pTinTri.get_Node(0);
                ITinNode n1 = pTinTri.get_Node(1);
                ITinNode n2 = pTinTri.get_Node(2);
                Console.Write(i.ToString() + ':');
                n0.GetHashCode();
                if (n1.Z >= 0 && n0.Z >= 0)
                {
                    point_start_x.Add(n0.X);
                    point_start_y.Add(n0.Y);
                    //终点
                    point_stop_x.Add(n1.X);
                    point_stop_y.Add(n1.Y);
                }
                if (n2.Z >= 0 && n1.Z >= 0)
                //赋值起点终点坐标，并去除重复
                //起点
                {
                    point_start_x.Add(n1.X);
                    point_start_y.Add(n1.Y);
                    //终点
                    point_stop_x.Add(n2.X);
                    point_stop_y.Add(n2.Y);
                }
                if (n2.Z >= 0 && n0.Z >= 0)
                //赋值起点终点坐标，并去除重复
                //起点
                {
                    point_start_x.Add(n2.X);
                    point_start_y.Add(n2.Y);
                    //终点
                    point_stop_x.Add(n0.X);
                    point_stop_y.Add(n0.Y);
                }
            }

            ITinRenderer pRenderNew = new TinEdgeRenderer() as ITinRenderer;
            ITinSingleSymbolRenderer pUVRenderer = pRenderNew as ITinSingleSymbolRenderer;
            ISimpleLineSymbol pSymbol = new SimpleLineSymbolClass();
            IRgbColor pRgbColor = new RgbColorClass();
            pRgbColor.Red = 255;
            pSymbol.Color = pRgbColor;
            pUVRenderer.Symbol = pSymbol as ISymbol;
            tinLayer.ClearRenderers();
            tinLayer.InsertRenderer(pRenderNew, 0);//插入一个渲染模型
            tinLayer.Name = "参考GNSS控制网型";
            axMapControl1.Map.AddLayer(tinLayer as ILayer);
            axMapControl1.Refresh();
            btnRefreshLayers_Click();
        }

        /// <summary>
        /// 点选GNSS控制点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 开始编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_mapControl.CurrentTool = null;
            mouseOperation = MouseOperation.SelectGNSSPoint;
            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
        }

        private void 结束编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_mapControl.CurrentTool = null;
            mouseOperation = MouseOperation.Default;
            m_mapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
        }

        private void 清空控制点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer pointLayer = Utils.GetLayerByName(m_mapControl, "GNSS控制点");
            if (pointLayer != null)
            {
                if (pointLayer.FeatureClass.FeatureCount(null) > 0)
                {
                    ITable pointLayerTable = pointLayer as ITable;
                    pointLayerTable.DeleteSearchedRows(null);
                }
            }
            m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }
        #endregion
        private IFeatureLayer CreateShpFromPoints(IPointCollection xjPointList, string xjFilePath)
        {

            int index = xjFilePath.LastIndexOf('\\');
            string xjFolder = xjFilePath.Substring(0, index);
            string xjShapeName = xjFilePath.Substring(index + 1);
            IWorkspaceFactory xjWsF = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace xjFWs = (IFeatureWorkspace)xjWsF.OpenFromFile(xjFolder, 0);

            if (File.Exists(xjFilePath))
            {
                File.Delete(xjFolder + "\\point.shp");
                File.Delete(xjFolder + "\\point.dbf");
                File.Delete(xjFolder + "\\point.prj");
                File.Delete(xjFolder + "\\point.shx");
            }

            IFields xjFields = new FieldsClass();
            IFieldsEdit xjFieldsEdit;
            xjFieldsEdit = (IFieldsEdit)xjFields;

            IField xjField = new FieldClass();
            IFieldEdit xjFieldEdit = (IFieldEdit)xjField;
            xjFieldEdit.Name_2 = "Shape";
            xjFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            IGeometryDef xjGeometryDef = new GeometryDefClass();
            IGeometryDefEdit xjGDefEdit = (IGeometryDefEdit)xjGeometryDef;
            xjGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            //定义坐标系
            //ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
            //ISpatialReference pSpatialReference = pSRF.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Beijing1954_3_Degree_GK_CM_114E);
            xjGDefEdit.SpatialReference_2 = this.axMapControl1.ActiveView.FocusMap.SpatialReference;//pSpatialReference;

            xjFieldEdit.GeometryDef_2 = xjGeometryDef;
            xjFieldsEdit.AddField(xjField);

            IFeatureClass xjFeatureClass;
            xjFeatureClass = xjFWs.CreateFeatureClass(xjShapeName, xjFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            IPoint xjPoint = new PointClass();

            for (int j = 0; j < xjPointList.PointCount; j++)
            {

                xjPoint.X = xjPointList.get_Point(j).X;
                xjPoint.Y = xjPointList.get_Point(j).Y;

                IFeatureBuffer xjFeature = xjFeatureClass.CreateFeatureBuffer();
                IFeatureCursor featureCursor = xjFeatureClass.Insert(true);

                xjFeature.Shape = xjPoint;
                xjFeature.set_Value(xjFeature.Fields.FindField("id"), j);
                featureCursor.InsertFeature(xjFeature);
            }

            IFeatureLayer xjFeatureLayer = new FeatureLayerClass();
            xjFeatureLayer.Name = xjShapeName;
            xjFeatureLayer.FeatureClass = xjFeatureClass;
            return xjFeatureLayer;
        }
        private IFeatureLayer CreateShpFromLine(string xjFilePath)
        {

            int index = xjFilePath.LastIndexOf('\\');
            string xjFolder = xjFilePath.Substring(0, index);
            string xjShapeName = xjFilePath.Substring(index + 1);
            IWorkspaceFactory xjWsF = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace xjFWs = (IFeatureWorkspace)xjWsF.OpenFromFile(xjFolder, 0);

            if (File.Exists(xjFilePath))
            {
                File.Delete(xjFolder + "\\line.shp");
                File.Delete(xjFolder + "\\line.dbf");
                File.Delete(xjFolder + "\\line.prj");
                File.Delete(xjFolder + "\\line.shx");
            }

            IFields xjFields = new FieldsClass();
            IFieldsEdit xjFieldsEdit;
            xjFieldsEdit = (IFieldsEdit)xjFields;

            IField xjField = new FieldClass();
            IFieldEdit xjFieldEdit = (IFieldEdit)xjField;
            xjFieldEdit.Name_2 = "Shape";
            xjFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            IGeometryDef xjGeometryDef = new GeometryDefClass();
            IGeometryDefEdit xjGDefEdit = (IGeometryDefEdit)xjGeometryDef;
            xjGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            //定义坐标系
            //ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
            //ISpatialReference pSpatialReference = pSRF.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Beijing1954_3_Degree_GK_CM_114E);
            xjGDefEdit.SpatialReference_2 = this.axMapControl1.ActiveView.FocusMap.SpatialReference;//pSpatialReference;

            xjFieldEdit.GeometryDef_2 = xjGeometryDef;
            xjFieldsEdit.AddField(xjField);

            IFeatureClass xjFeatureClass;
            xjFeatureClass = xjFWs.CreateFeatureClass(xjShapeName, xjFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            IPoint startPoint = new PointClass();
            IPoint stopPoint = new PointClass();
            IPolyline xjLine = new PolylineClass();
            for (int j = 0; j < point_start_x.Count; j++)
            {

                startPoint.X = Convert.ToDouble(point_start_x[j]);
                startPoint.Y = Convert.ToDouble(point_start_y[j]);
                stopPoint.X = Convert.ToDouble(point_stop_x[j]);
                stopPoint.Y = Convert.ToDouble(point_stop_y[j]);
                //Console.WriteLine("起点X：" + startPoint.X);
                //Console.WriteLine("起点Y：" + startPoint.Y);
                //Console.WriteLine("终点X：" + stopPoint.X);
                //Console.WriteLine("终点Y：" + stopPoint.Y);
                //xjLine.PutCoords(startPoint, stopPoint);
                xjLine.FromPoint = startPoint;
                xjLine.ToPoint = stopPoint;
                IFeatureBuffer xjFeature = xjFeatureClass.CreateFeatureBuffer();
                IFeatureCursor featureCursor = xjFeatureClass.Insert(true);

                xjFeature.Shape = xjLine;
                xjFeature.set_Value(xjFeature.Fields.FindField("id"), j);
                featureCursor.InsertFeature(xjFeature);
            }

            IFeatureLayer xjFeatureLayer = new FeatureLayerClass();
            xjFeatureLayer.Name = xjShapeName;
            xjFeatureLayer.FeatureClass = xjFeatureClass;
            return xjFeatureLayer;
        }
        private void 生成基线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strShapeFolder = System.Environment.CurrentDirectory;
            string strShapeFile = "\\Temp\\line.shp";
            string shapeFileFullName = strShapeFolder + strShapeFile;
            if (editable == false)
            {
                pFeatureLayer_line = CreateShpFromLine(shapeFileFullName);
                MessageBox.Show("三角网生成完成！");
            }
            else
                MessageBox.Show("请先点击选点！");
            pFeatureLayer_line.Name = "GNSS网基线(线要素)";
            axMapControl1.Map.AddLayer(pFeatureLayer_line as ILayer);
            btnRefreshLayers_Click();
            
        }
        private void btnRefreshLayers_Click()
        {
            //清空原有选项
            GNSSLE.cboLayers.Items.Clear();
            //没有添加图层时返回

            if (this.axMapControl1.Map.LayerCount == 0)
            {
                //MessageBox.Show("MapControl中未添加图层！", "提示");
                return;
            }
            //加载图层
            for (int i = 0; i < this.axMapControl1.Map.LayerCount; i++)
            {
                ILayer pLayer = this.axMapControl1.get_Layer(i);
                GNSSLE.cboLayers.Items.Add(pLayer.Name);
            }
            this.axMapControl1.Refresh();
            GNSSLE.cboLayers.SelectedIndex = 0;

        }
        public void btnSave_Click()
        {
            //判断编辑是否初始化
            if (mEdit == null)
                return;
            //处于编辑状态且已编辑则保存
            if (mEdit.IsEditing() && mEdit.HasEdited())
            {
                mEdit.SaveEditing(true);
                MessageBox.Show("保存成功啦！");
            }
        }
        //结束编辑
        public void btnStopEditing_Click()
        {
            if (mEdit == null)
            {
                MessageBox.Show("您尚未进行任何修改，无需保存！");
                return;
            }
            if (mEdit.HasEdited())
            {
                DialogResult dr = MessageBox.Show("图层已编辑，是否保存？", "提示", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.OK)
                {

                    mEdit.SaveEditing(true);
                    MessageBox.Show("保存成功啦！");
                    mEdit = null;
                }
                else
                    mEdit.SaveEditing(false);
            }
            else mEdit = null;
            GNSSLE.btnStartEditing.Enabled = true;
            GNSSLE.cboTasks.Enabled = true;
            GNSSLE.btnStopEditing.Enabled = false;
            GNSSLE.btnSave.Enabled = true;
        }
        public void btnStartEditing_Click()
        {

            axMapControl1.MousePointer = ESRI.ArcGIS.Controls.esriControlsMousePointer.esriPointerCustom;
            //判断是否存在可编辑图层
            if (this.axMapControl1.Map.LayerCount == 0)
                return;
            if (GNSSLE.cboLayers.Items.Count == 0)
            {
                MessageBox.Show("请选择要编辑的图层", "提示");
                return;
            }

            //获取编辑图层
            IMap pMap = this.axMapControl1.Map;
            //IFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(cboLayers.SelectedIndex) as IFeatureLayer;
            //MessageBox.Show(this.axMapControl1.get_Layer(cboLayers.SelectedIndex).GetType().ToString());
            ILayer pFeatureLayer = this.axMapControl1.get_Layer(GNSSLE.cboLayers.SelectedIndex) as ILayer;
            //pFeatureLayer.
            //初始化编辑
            if (mEdit == null)
            {
                mEdit = new GNSSEdit(pFeatureLayer as IFeatureLayer, pMap);
            }
            //开始编辑
            mEdit.StartEditing();
            //开始编辑设为不可用，将其他编辑按钮设为可用
            GNSSLE.btnStartEditing.Enabled = false;
            GNSSLE.cboTasks.Enabled = true;
            GNSSLE.btnStopEditing.Enabled = true;
            GNSSLE.btnSave.Enabled = true;
        }

        private void 基线编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
            GNSSLE.Show(this);
        }

        private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {

            //判断是否鼠标左键
            if (e.button != 1)
                return;
            //判断是否处于编辑状态
            if (mEdit != null)
            {
                if (mEdit.IsEditing())
                {
                    switch (GNSSLE.cboTasks.SelectedIndex)
                    {
                        case 0:
                            break;
                        case 1:
                            mEdit.PanMouseUp(e.mapX, e.mapY);
                            break;
                    }
                }
            }
        }
        private void axMapControl1_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e)
        {
            //判断是否鼠标左键
            if (e.button != 1)
                return;
            //判断是否处于编辑状态
            if (mEdit.IsEditing())
            {
                switch (GNSSLE.cboTasks.SelectedIndex)
                {
                    case 0:
                        mEdit.CreateDoubleClick(e.mapX, e.mapY);
                        break;
                    case 1:
                        break;
                }
            }
        }

    }
}